package com.lintf.jwt.security;

import com.lintf.jwt.entity.User;
import com.lintf.jwt.entity.UserPermissions;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ system:Window
 * @ author:lin tingfeng
 * @ data:2022/3/15-16:33
 * @ package_name:com.lintf.jwt.security
 * @ project_name:SpringSecurity-JWT
 * @ desc:实现UserDetails接口并实现方法
 */
public class AdminUserDetails implements UserDetails {

    private User user;
    private List<UserPermissions> permissionList;

    public AdminUserDetails(User user, List<UserPermissions> permissionList) {
        this.user = user;
        this.permissionList = permissionList;
    }

    /**
     * 得到授权，返回权限
     *
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return permissionList.stream()
                .filter(umsPermission -> umsPermission.getValue() != null)
                .map(umsPermission -> new SimpleGrantedAuthority(umsPermission.getValue()))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    /**
     * 账号未过期
     *
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 账号未锁定
     *
     * @return
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 账号凭证是否过期
     *
     * @return
     */

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 账号是否启用
     *
     * @return
     */
    @Override
    public boolean isEnabled() {
        return user.getStatus().equals(1);
    }
}


